const router = require("koa-router")();
const DB = require("../../module/db");
const { exec } = require('child_process');
const sd = require("silly-datetime");
const images = require("images")
const picture = require("./media/picture")
const stringRandom = require("string-random")
const os = require('os')

router.get("/", async (ctx) => {
    ctx.body = "后台media首页";

}).get("/getVideoUrl", async (ctx) => {
    let fileId = ctx.query["fileId"];
    let type = ctx.query["type"]
    if (type === "quicktime")
        type = "mov"
    let randomStr = stringRandom(16)
    let data = await DB.downloadFile(DB.getObjectId(fileId), '/tmp/'+randomStr+'.'+type);
    let sumTime = await DB.findSomeCol('media', {"fileId": DB.getObjectId(fileId)}, {"_id":0, "sumTime":1});
    if (data !== 1){
        ctx.body = 0;
    } else {
        let executeStr = "ffmpeg -re -i /tmp/" + randomStr + "." + type + " " +
            "-c:v libx264 -preset superfast -tune zerolatency " +
            "-c:a aac -strict -2 -ar 44100 -f flv " +
            "rtmp://localhost:1935/live/" + randomStr;
        exec(executeStr, (error, stdout, stderr) => {
            if (error) {
                console.error(`执行的错误: ${error}`);
            }
            // console.log(`stdout: ${stdout}`);
        });
        ctx.body = {
            url: "http://120.224.199.213:8000/live/" + randomStr + ".flv",
        sumTime: sumTime[0].sumTime
        };
    }

}).post("/uploadMedia", async (ctx) => {
    const file = ctx.request.files.file;
    let userId = ctx.request.body.userId;
    let userName = ctx.request.body.userName
    let reviewId = ctx.request.body.reviewId;
    let arr = file.type.split("/")
    let str = "mv " + file.path + " /tmp/" + file.name

    if (arr[0] === "video") //视频文件
        exec('ffmpeg -ss 00:00:01 -i ' + file.path + " -y -f image2 -t 0.001 /tmp/" + file.name.split(".")[0] + ".jpg", async function(err,stdout,stderr){
            let outStr = stderr.toString();
            let regDuration =/Duration\: ([0-9\:\.]+),/;
            let rs = regDuration.exec(outStr);
            let hms = rs[1].split(":")
            let h = + hms[0]
            let m = + hms[1]
            let s = + hms[2]
            let time = (h * 60 * 60 + m * 60 + s) * 1000
            let buffer = images("/tmp/" + file.name.split(".")[0] + ".jpg").encode("png", {quality: 10})

            let data1 = await DB.uploadFile(file.path, file.name);
            let fileId = data1["_id"]
            let data2 = await DB.insert('media',
                {"userId": userId, "userName": userName, "fileId": fileId, "name": file.name.split(".")[0], "buffer": buffer, "sumTime": time, "type": file.type, "like": 0});
            let data3 = await DB.addArray("review", {"_id": DB.getObjectId(reviewId)}, {"mediaId": data2.ops[0]._id})
            if (data2.result.ok && data3.result.ok) {
                console.log("文件" + file.name + "保存成功")
                ctx.body = 1
            } else {
                console.log("文件" + file.name + "保存失败")
                ctx.body = 0
            }
        })
    else    //图片文件
        exec(str, async function(error,stdout,stderr){
            if (error) {
                console.error(`执行的错误: ${error}`);
                ctx.body = 0
            }
            let buffer = images("/tmp/" + file.name).encode("png", {quality: 10})
            let data1 = await DB.uploadFile("/tmp/" + file.name, file.name);
            let fileId = data1["_id"]
            let data2 = await DB.insert('media',
                {"userId": userId, "userName": userName, "fileId": fileId, "name": file.name.split(".")[0], "buffer": buffer, "type": file.type, "like": 0});
            let data3 = await DB.addArray("review", {"_id": DB.getObjectId(reviewId)}, {"mediaId": data2.ops[0]._id})
            if (data2.result.ok && data3.result.ok) {
                console.log("文件" + file.name + "保存成功")
                ctx.body = 1
            } else {
                console.log("文件" + file.name + "保存失败")
                ctx.body = 0
            }
        })

}).get("/getAtlasMedia", async (ctx) => {
    ctx.compress = true
    ctx.body = await DB.findSomeCol('media', {"atlasId": ctx.query["atlasId"]}, {"like":0});

}).post("/getReviewMedia", async (ctx) => {
    ctx.compress = true
    let data = ctx.request.body["id"]
    let list = []
    for (let i = 0; i < data.length; i ++) {
        let result = await DB.find("media", {"_id": DB.getObjectId(data[i])})
        list.push(result[0])

    }
    ctx.body = list

}).post("/deleteMedia", async (ctx) => {
    let mediaId = ctx.request.body.id;
    let fileId = ctx.request.body.fileId;
    let reviewId = ctx.request.body.reviewId
    let time = sd.format(new Date(), 'YYYY-MM-DD HH:mm');
    let data1 = await DB.remove1('media', {"_id": DB.getObjectId(mediaId)});
    if (data1.result.ok) {
        let data2 = await DB.remove1('fs.files', {"_id": DB.getObjectId(fileId)});
        let data3 = await DB.remove2('fs.chunks', {"files_id": DB.getObjectId(fileId)});
        if (data2.result.ok && data3.result.ok) {
            let data4 = await DB.remove2('comment', {"mediaId": mediaId});
            if (data4.result.ok) {
                let data5 = await DB.findSomeCol('tagging', {'mediaId': mediaId}, {"_id": 0, "fileId": 1});
                if (data5.length > 0) {
                    let fileId2 = data5[0]["fileId"];
                    let data6 = await DB.remove2('fs.files', {"_id": DB.getObjectId(fileId2)});
                    let data7 = await DB.remove2('fs.chunks', {"files_id": DB.getObjectId(fileId2)});
                    let data8 = await DB.remove2('tagging', {'mediaId': mediaId});
                    if (data6.result.ok && data7.result.ok && data8.result.ok) {
                        await DB.deleteArray('review', {"_id": DB.getObjectId(reviewId)}, {"mediaId": DB.getObjectId(mediaId)})
                        ctx.body = 1;
                        console.log(time + "：删除媒体文件及其评论成功" + ctx.request.body["id"]);
                    } else {
                        ctx.body = 0;
                        console.log(time + "：删除媒体文件成功，删除标记失败" + ctx.request.body["id"]);
                    }
                } else {
                    await DB.deleteArray('review', {"_id": DB.getObjectId(reviewId)}, {"mediaId": DB.getObjectId(mediaId)})
                    ctx.body = 1;
                    console.log(time + "：删除媒体文件及其评论成功" + ctx.request.body["id"]);
                }
            } else {
                ctx.body = 0;
                console.log(time + "：删除媒体文件成功，删除评论失败" + ctx.request.body["id"]);
            }
        } else {
            ctx.body = 0;
            console.log(time + "：删除媒体文件及其评论失败" + ctx.request.body["id"]);
        }
    } else {
        ctx.body = 0;
        console.log(time + "：删除媒体文件及其评论失败" + ctx.request.body["id"]);
    }

}).use('/picture', picture);

///获取本机ip///
// function getIPAdress() {
//     let interfaces = os.networkInterfaces();
//     for (let devName in interfaces) {
//         let iface = interfaces[devName];
//         for (let i = 0; i < iface.length; i++) {
//             let alias = iface[i];
//             if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
//                 return alias.address;
//             }
//         }
//     }
// }

module.exports = router.routes();
